/*
 * ====================================================================
 * Copyright (C) 2013 Eric Blond
 *
 * This file is part of Neptune.
 *
 * Neptune is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Neptune is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Neptune.  If not, see <http://www.gnu.org/licenses/>.
 * ====================================================================
 */

package com.hyperplan.neptune.command;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommandManager {

	private List<Command> commands;

	public CommandManager() {
		commands = new ArrayList<Command>();
		commands.add(new LexCommand());
	}
	
	public void run(String[] arguments) {
		try {
			if (arguments.length < 1) {
				throw new Exception("No arguments");
			}
			String commandArg = arguments[0].toLowerCase();
			for (Command command : commands) {
				List<String> parameters = Arrays.asList(command.getParameters());
				if (command.getName().equals(commandArg)) {
					Map<String, String> mapping = new HashMap<String, String>();
					for (int i = 1; i < arguments.length; i++) {
						String argument = arguments[i];
						if (!argument.startsWith("--")) {
							throw new Exception(
									String.format("Invalid argument [%s]", argument));
						}
						int index = argument.indexOf('=');
						if (index == -1) {
							throw new Exception(
									String.format("Invalid argument [%s]", argument));
						}
						String key = argument.substring(2, index);
						String value = argument.substring(index + 1);
						if (value.isEmpty()) {
							throw new Exception(
									String.format("Invalid argument [%s]", argument));
						}
						if (parameters.contains(key)) {
							mapping.put(key, value);
						} else {
							throw new Exception(
									String.format("Parameter [%s] not accepted", key));
						}
					}
					command.execute(mapping);
					System.exit(0);
				}
			}
			throw new Exception(String.format("Unknown command [%s]", arguments[0]));
		}
		catch (Exception exception) {
			exception.printStackTrace(System.err);
			System.exit(-1);
		}
	}
}
